import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 10000
})

// 请求拦截器 - 添加token到请求头
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理token过期
api.interceptors.response.use(
  response => {
    return response
  },
  async error => {
    const originalRequest = error.config
    
    // 如果是401错误且没有重试过
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      
      const retoken = localStorage.getItem('retoken')
      if (retoken) {
        try {
          // 尝试使用刷新token获取新的访问token
          const refreshResponse = await axios.post('http://localhost:8000/accounts/refresh-token/', {
            refresh_token: retoken
          })
          
          if (refreshResponse.data.token) {
            localStorage.setItem('token', refreshResponse.data.token)
            originalRequest.headers.Authorization = `Bearer ${refreshResponse.data.token}`
            return api(originalRequest)
          }
        } catch (refreshError) {
          // 刷新token也过期，清除本地存储并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('retoken')
          localStorage.removeItem('user')
          router.push('/auth')
        }
      } else {
        // 没有刷新token，直接跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('retoken')
        localStorage.removeItem('user')
        router.push('/auth')
      }
    }
    
    return Promise.reject(error)
  }
)

// 将axios实例挂载到全局
const app = createApp(App)
app.config.globalProperties.$api = api
app.config.globalProperties.$axios = axios

app.use(router).mount('#app')
